package com.jvk.check4home.frwk;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.util.Log;

import com.dreasyLib.storage.ShareObjectManager;
import com.jvk.check4home.R;
import com.pras.SpreadSheet;
import com.pras.SpreadSheetFactory;
import com.pras.WorkSheet;
import com.pras.WorkSheetCell;
import com.pras.WorkSheetRow;
import com.pras.table.Record;

public class frwk {

	public ShareObjectManager shareManager;
	public ArrayList<homeDTO> listBuildings;
	public SpreadSheetFactory factory;
	private static frwk instance=null;
	private Context _myContext;
	private SpreadSheet spread;
	private WorkSheet myWorkingShet;
	public boolean reload;
	public static frwk getInstance(Context myContext)
	{
		if (instance==null)
		{
			instance=new frwk(myContext);	
		}
		return instance;
	}


	protected frwk(Context myContext)
	{
		_myContext=myContext;
		reload=true;
		shareManager=new ShareObjectManager(_myContext);
	}

	public void setConfiguration(String user, String pass, String filename,String spreedame)
	{
		shareManager.SaveConfig(constants.USER, user);
		shareManager.SaveConfig(constants.PASWORD, pass);
		shareManager.SaveConfig(constants.PAGE_NAME, filename);
		shareManager.SaveConfig(constants.SPREED_NAME, spreedame);		
	}


	public OutputState loadBuildingList() {
		String user=shareManager.LoadConfig(constants.USER);
		String pass=shareManager.LoadConfig(constants.PASWORD);
		Log.d("gdata","login with ["+user+"] ["+pass+"]");
		factory = SpreadSheetFactory.getInstance(user,pass);
		if (factory==null)
		{
			return new OutputState(constants.STATE_NULL, "factory is null");
		}
		//---------------------------------------------------//
		ArrayList<SpreadSheet> myList=null;
		try{
			myList = factory.getAllSpreadSheets(true);
		}catch (Exception e) {
			return new OutputState(constants.STATE_USER, "user is invalid");
		}
		spread=findSpread(myList,shareManager.LoadConfig(constants.PAGE_NAME));
		if (spread!=null)
		{
			Log.d("gdata", "created, i have to access");
			spread=factory.getSpreadSheet(shareManager.LoadConfig(constants.PAGE_NAME), true).get(0);
		}else
		{
			createRemoteFile();
			myList = factory.getAllSpreadSheets(true);
			spread=findSpread(myList, shareManager.LoadConfig(constants.PAGE_NAME));
		}

		ArrayList<WorkSheet> listWs = spread.getAllWorkSheets(true);
		myWorkingShet = findWSet(listWs,shareManager.LoadConfig(constants.SPREED_NAME));

		ArrayList<WorkSheetRow> cells = myWorkingShet.getData();
		ArrayList<Record> records = myWorkingShet.getRecords(spread.getKey());
		int maxrecords=0;
		if( records!=null)Log.d("gdata","purging count ["+String.valueOf(cells.size())+"]< ["+String.valueOf(records.size())+"]");
		if (records!=null)maxrecords=records.size();
		if ((cells!=null)&&
				(maxrecords<cells.size())
		)
		{
			purgueHomes(myWorkingShet,spread,cells,maxrecords);
			records = myWorkingShet.getRecords(spread.getKey());
		}
		listBuildings=homeFactory(records);
		for (homeDTO casa : listBuildings) {
			Log.d("gdata","Parsed! ["+casa.name+"]+ ["+casa.toString()+"]");
		}
		//---------------------------------------------------//
		return new OutputState(constants.STATE_OK, "");
	}



	private void purgueHomes(WorkSheet ws,SpreadSheet spread, ArrayList<WorkSheetRow> cells, int maxrecords) {
		for (int i=maxrecords;i<cells.size();i++) {
			HashMap<String, String> rs =createMapFromDto(new homeDTO());
			ArrayList<WorkSheetCell> celdas = cells.get(i).getCells();
			String last="";
			for (WorkSheetCell workSheetCell : celdas) {
				Log.d("gdata", "name ["+workSheetCell.getName()+"] value ["+workSheetCell.getValue()+"] ["+workSheetCell.getType()+"]");
				if (last.equals(workSheetCell.getName()))
				{
					rs.put(workSheetCell.getName(),rs.get(workSheetCell.getName()).concat(parseToUrl(workSheetCell.getValue())));
				}else{
					rs.put(workSheetCell.getName(),parseToUrl(workSheetCell.getValue()));
					last=workSheetCell.getName();
				}
			}
			Log.d("gdata","purging..["+rs.toString()+"]");
			ws.addRecord(spread.getKey(), rs);
		}

	}

	private ArrayList<homeDTO> homeFactory(ArrayList<Record> Myrecords2) {
		ArrayList<homeDTO> listHomes=new ArrayList<homeDTO>();
		homeDTO home=null;
		String[] resources=_myContext.getResources().getStringArray(R.array.fields);
		if (Myrecords2!=null)
		{
			for (Record myrecord : Myrecords2) {
				home=new homeDTO();
				home.name=			myrecord.getData().get(resources[0]);
				home.rooms=			myrecord.getData().get(resources[1]);
				home.bathrooms=		myrecord.getData().get(resources[2]);
				home.flat_number=	myrecord.getData().get(resources[3]);
				home.scuareM=		myrecord.getData().get(resources[4]);
				home.elevators=		myrecord.getData().get(resources[5]);
				home.commonPlaces=	myrecord.getData().get(resources[6]);
				home.parkings=		myrecord.getData().get(resources[7]);
				home.r_bathrooms=	myrecord.getData().get(resources[8]);
				home.r_kitchen=		myrecord.getData().get(resources[9]);
				home.r_floor=		myrecord.getData().get(resources[10]);
				home.r_outside=		myrecord.getData().get(resources[11]);
				home.r_rooms=		myrecord.getData().get(resources[12]);
				home.r_doublewindows=myrecord.getData().get(resources[13]);
				home.r_muebles=		myrecord.getData().get(resources[14]);
				home.r_bathroom_Date=myrecord.getData().get(resources[15]);
				home.phone_cable=	myrecord.getData().get(resources[16]);
				home.gas_electricity=myrecord.getData().get(resources[17]);
				home.bus_distance=	myrecord.getData().get(resources[18]);
				home.metro_distance=myrecord.getData().get(resources[19]);
				home.community=		myrecord.getData().get(resources[20]);
				home.price=			myrecord.getData().get(resources[21]);
				home.comments=		myrecord.getData().get(resources[22]);
				home.personal_score=myrecord.getData().get(resources[23]);
				home.contact_mail=	myrecord.getData().get(resources[24]);
				home.web=			parseToUrl(myrecord.getData().get(resources[25]));
				home.phone=			myrecord.getData().get(resources[26]);
				home.call_horary=	myrecord.getData().get(resources[27]);
				home.latit=			myrecord.getData().get(resources[28]);
				home.longit=		myrecord.getData().get(resources[29]);
				home.pos=listHomes.size();
				listHomes.add(home);
			}
		}
		return listHomes;
	}


	private void createRemoteFile()
	{
		Log.d("gdata", "creating it");
		factory.createSpreadSheet(shareManager.LoadConfig(constants.PAGE_NAME));
		ArrayList<SpreadSheet> myList = factory.getAllSpreadSheets(true);
		Log.d("gdata", "number of spreedshets ["+myList.size()+"]");
		String[] arrStr=_myContext.getResources().getStringArray(R.array.fields);
		SpreadSheet spread=findSpread(myList,shareManager.LoadConfig(constants.PAGE_NAME));
		spread.addWorkSheet(shareManager.LoadConfig(constants.SPREED_NAME),"pisos", 3, arrStr);
	}


	private String getField(int pos)
	{
		return _myContext.getResources().getStringArray(R.array.fields)[pos];
	}

	private WorkSheet findWSet(ArrayList<WorkSheet> listWs, String string) {
		int number=0;
		while ((listWs.size()>number))
		{
			Log.d("gdata", "------comparing ["+listWs.get(number).getTitle()+"] ["+string+"]");
			if (listWs.get(number).getTitle().equals(string))
			{
				return listWs.get(number);
			}
			number=number+1;
		}
		return null;
	}

	private SpreadSheet findSpread(ArrayList<SpreadSheet> myList,String myPisos) {
		int number=0;
		while ((myList.size()>number))
		{
			Log.d("gdata", "------comparing ["+myList.get(number).getTitle()+"] ["+myPisos+"]");
			if (myList.get(number).getTitle().equals(myPisos))
			{
				return myList.get(number);
			}
			number=number+1;
		}
		return null;
	}


	public void addNewhome(homeDTO homeToAdd)
	{
		Log.d("gdata","Creating new home at ["+homeToAdd.name+"]");
		HashMap<String, String> rs = createMapFromDto(homeToAdd);
		myWorkingShet.addRecord(spread.getKey(), rs);
	}


	private HashMap<String, String> createMapFromDto(homeDTO homeToAdd) {
		HashMap<String, String> rs = new HashMap<String, String>();
		rs.put(getField(0), homeToAdd.name);
		rs.put(getField(1), homeToAdd.rooms);
		rs.put(getField(2), homeToAdd.bathrooms);
		rs.put(getField(3), homeToAdd.flat_number);
		rs.put(getField(4), homeToAdd.scuareM);
		rs.put(getField(5), homeToAdd.elevators);
		rs.put(getField(6), homeToAdd.commonPlaces);
		rs.put(getField(7), homeToAdd.parkings);
		rs.put(getField(8), homeToAdd.r_bathrooms);
		rs.put(getField(9), homeToAdd.r_kitchen);
		rs.put(getField(10), homeToAdd.r_floor);
		rs.put(getField(11), homeToAdd.r_outside);
		rs.put(getField(12), homeToAdd.r_rooms);
		rs.put(getField(13), homeToAdd.r_doublewindows);
		rs.put(getField(14), homeToAdd.r_muebles);
		rs.put(getField(15), homeToAdd.r_bathroom_Date);
		rs.put(getField(16), homeToAdd.phone_cable);
		rs.put(getField(17), homeToAdd.gas_electricity);
		rs.put(getField(18), homeToAdd.bus_distance);
		rs.put(getField(19), homeToAdd.metro_distance);
		rs.put(getField(20), homeToAdd.community);
		rs.put(getField(21), homeToAdd.price);
		rs.put(getField(22), homeToAdd.comments);
		rs.put(getField(23), homeToAdd.personal_score);
		rs.put(getField(24), homeToAdd.contact_mail);
		rs.put(getField(25), parseToUrl(homeToAdd.web));
		rs.put(getField(26), homeToAdd.phone);
		rs.put(getField(27), homeToAdd.call_horary);
		rs.put(getField(28), homeToAdd.latit);
		rs.put(getField(29), homeToAdd.longit);
		return rs;
	}
	private String parseToUrl(String web) {
		String parsered=web.replace("&", "&amp;");
		parsered=parsered.replace("http_//", "http://");
		parsered=parsered.replace("https_//", "https://");
		Log.d("gdata","----->"+parsered);
		return parsered;
	}


	public void updateNewhome(homeDTO localHome,homeDTO homeToAdd)
	{

		try {
			String founded=getField(0)+"=\""+URLEncoder.encode(localHome.name,"UTF8")+"\"";
			Log.d("gdata","____Updateing new home at ["+homeToAdd.name+"] ["+founded+"] from ["+localHome.name+"]");
			ArrayList<Record> list = myWorkingShet.getRecords(spread.getKey());

			if ((list!=null)&&(list.size()>0))
			{

				Log.d("gdata", "_____ENCONTRADO!!!:["+String.valueOf(list.size())+"]");        
				Record record=findRecord(localHome,list);
				if (record!=null){//TODO probar por que no funciona el de la query.. tiene webs
					record.setData(createMapFromDto(homeToAdd));
					myWorkingShet.updateRecord(record);
				}
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}


	private Record findRecord(homeDTO localHome, ArrayList<Record> list) {
		Record record=null;
		int i=0;
		while (i<list.size())
		{
			record=list.get(i);
			if (record.getData().get(getField(0)).equals(localHome.name))
			{
				return record;
			}else
			{
				i=i+1;
			}
		}
		return record;
	}




}
